package cn.edu.ncu.housinghub.controller.message;

import cn.edu.ncu.housinghub.dto.chat.ChatMessageDTO;
import cn.edu.ncu.housinghub.entity.chatsession.ChatMessage;
import cn.edu.ncu.housinghub.service.ChatService;
import lombok.RequiredArgsConstructor;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.security.Principal;

/**
 * 发送、查询消息
 */
@Controller
@RequiredArgsConstructor
public class MessageController {
    private final ChatService chatService;
    private final SimpMessagingTemplate messagingTemplate;

    /**
     * 处理客户端发送的消息
     */
    @MessageMapping("/chat/send")
    public void handleMessage(ChatMessageDTO messageDTO, Principal principal) {
        try {
            // 从Principal中获取当前登录用户ID
            Long senderId = Long.parseLong(principal.getName());

            System.out.println("🔍 收到WebSocket消息: " + messageDTO);
            System.out.println("🔍 发送者ID: " + senderId);

            // 发送消息
            ChatMessage message = chatService.sendMessage(senderId, messageDTO);

            System.out.println("✅ 消息保存成功，消息ID: " + message.getMessageId());

            // 直接推送消息给接收者（同步推送，确保实时性）
            String destination = "/user/" + messageDTO.getReceiverId() + "/queue/chat";
            messagingTemplate.convertAndSend(destination, message);

            System.out.println("✅ 消息推送成功到: " + destination);

            // 推送未读消息数量更新给接收者
            try {
                int unreadCount = chatService.getUnreadCount(message.getSessionId(), message.getReceiverId());
                String unreadDestination = "/user/" + message.getReceiverId() + "/queue/unread";
                messagingTemplate.convertAndSend(unreadDestination,
                    "{\"sessionId\":" + message.getSessionId() + ", \"count\":" + unreadCount + "}");
                System.out.println("✅ 未读消息数量推送成功: " + unreadCount);
            } catch (Exception unreadEx) {
                System.err.println("❌ 推送未读消息数量失败: " + unreadEx.getMessage());
            }

        } catch (Exception e) {
            System.err.println("❌ 处理WebSocket消息失败: " + e.getMessage());
            e.printStackTrace();

            // 发送错误消息给发送者
            String errorDestination = "/user/" + principal.getName() + "/queue/error";
            messagingTemplate.convertAndSend(errorDestination, "消息发送失败: " + e.getMessage());
        }
    }

    /**
     * 标记消息为已读
     */
    @MessageMapping("/chat/read")
    public void markAsRead(Long sessionId, Principal principal) {
        Long userId = Long.parseLong(principal.getName());
        chatService.markAsRead(sessionId, userId);
    }
}
